package cn.iocoder.yudao.module.handguard.tool.http;

import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.module.handguard.tool.Base64ToFile;
import cn.iocoder.yudao.module.handguard.tool.MD5Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


/**
 * HTTP 工具类
 *
 * @author 芋道源码
 */
public class VCodeHttpUtils {
    //环境路径  /opt/yzm
    private static final String filePath = "/opt/yzm/";
    private static final String fileWinPath = "D:\\testimg\\";
    private static final Logger log = LoggerFactory.getLogger(VCodeHttpUtils.class);


//    /**
//     * 获取贝壳租房网搜索结果
//     *
//     * @param param 要搜索的关键字
//     * @return 房源总价格
//     */
//    public static String getBkeHousingResForSearch(String param) {
//        try {
//
//            HttpUtils httpUtils = new HttpUtils();
//            // 从URL获取HTML内容
//            String html = HttpUtil.createGet("https://cq.ke.com/xiaoqu/rs" + param + "/")
//                    //.header("cookie","hip=gsenNjmNpI_mIM-ScpTa2PQZG9uuvFSUEJONlJSE-Xuizpe8pj6bGomfX2PD36TNG80oOdXEKm_JyIAMF4J3l23bfZI3KGDqfucrfSKEdJMMbc4JdiBb47_zf7g-hAQVD476TXjNh30JbS53PaR8DdBYrjbLWmo39NrxBJHZQSr0SexAtLY%3D")
//                    .header("cookie","lianjia_ssid=0d22904c-8a66-490c-b700-34b4863e553e; lianjia_uuid=dd967ea1-5eb5-4175-9d31-08c7d6980b9f; select_city=500000; HMACCOUNT=4E56DB5BCF10EECC; sajssdk_2015_cross_new_user=1; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22191c55d170f1263-07d81b9e9f24f3-17525637-2073600-191c55d17102644%22%2C%22%24device_id%22%3A%22191c55d170f1263-07d81b9e9f24f3-17525637-2073600-191c55d17102644%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_referrer%22%3A%22%22%2C%22%24latest_referrer_host%22%3A%22%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%7D%7D; crosSdkDT2019DeviceId=-mzx64c--y3e1di-j86sphrvvvjkkmy-1dgs3jgns; lfrc_=ab5cfec2-f24c-45f9-80c2-f7bd10262dea; hip=GNH2bw_x312bP1V-eIJwWaayg_11bD8rvMGgVm5wBBBvRMyceHLEK0wI5VcbQ4_x5sX8Q5H5ckNXrAlgST8y671fAvtXwYNTYPsUrxs6-YV4aaTqPCKcCfpR-M9nZsAieCQX2FOwImTPS4azM-7KAqI9xryUeJky-WBHpTozApys4WwwHCU%3D; Hm_lvt_b160d5571570fd63c347b9d4ab5ca610=1725601946; Hm_lpvt_b160d5571570fd63c347b9d4ab5ca610=1725601979; srcid=eyJ0Ijoie1wiZGF0YVwiOlwiYzVmMzIzYjYyZjAyMGEyMjY0Zjk4MTMwMWZkN2RhZTViMzY0ZGVhNDRmY2I2NGRkYzYyY2ZlYzFjYTUwODk5NjZhMGU2ZDZhZDczZWFiZmQ2NGRhYWZlNTQxMGQ3MTljODQyNzU3YTJkNmY1M2NjM2EwMjAwNjMzNmYxOTdlMGUxMzA1ZjI3Nzc5YzMyZTIyM2I4ZjI0ZWUxNDIwZjNhMzEwNWZmM2JiM2UwN2UxNGUxMzI1NzcyM2M5YTVjYWEzODFkMDc4OGU5NWRkNGFkYjRiNjllYTYyMzQ5YzI3ZTdlMjc3M2I5ZTI3ZmE2MjdiYjYzMGVlYjRhM2ZkY2I0YVwiLFwia2V5X2lkXCI6XCIxXCIsXCJzaWduXCI6XCJhMDQ2OTc5MlwifSIsInIiOiJodHRwczovL2NxLmtlLmNvbS94aWFvcXUvcnMvIiwib3MiOiJ3ZWIiLCJ2IjoiMC4xIn0=; login_ucid=2000000101852215; lianjia_token=2.00106ea83b6ce7e1e001c3810a26494a32; lianjia_token_secure=2.00106ea83b6ce7e1e001c3810a26494a32; security_ticket=WKUTqd5+eqCnqvS11FyZUfj67P887+XhEKNygnMa9StzfNgvTlE4M6FL2SqJ548wE8KFL0kbnW1xX5rA98eiiuLa0uoM4CAdzO6UY60CgdJOWHuwhCq4TZKVydTS5xD0fZkAGTnEB98pZrVc8jBuxntPqZrO88/iDvp/6KFBN/4=")
//                    .execute()
//                    .body();
//
//            // 使用Jsoup解析HTML
//            Document doc = Jsoup.parse(html);
//
//            // 获取页面中第一个<div>元素属性
//            Element firstDiv = doc.getElementsByClass("totalPrice").first();
//            Element classValue = firstDiv.getElementsByTag("span").first();
//
//            // 输出结果
//            return classValue.html();
//        } catch (Exception e) {
//            //log.error("获取到数据异常", e);
//        }
//        return "";
//    }

    public static String getBkeHousingResForSearch(String param) {
        String url = "https://cq.ke.com/xiaoqu/rs" + param + "/";
        //更换为实际的验证码图片URL
        String captchaUrl = "https://captcha.lianjia.com/captcha/resource?sceneId=sec-hip&token=";
        String captchaValidateUrl = "https://captcha.lianjia.com/captcha/pre-validate?sceneId=sec-hip&token=";
        //验证 token以及 ext
        String validateUrl  = "https://hip.ke.com/api/v1/validate";
        try {
            // 从URL获取HTML内容
            String html = HttpUtil.createGet(url)
                    //.header("cookie","hip=gsenNjmNpI_mIM-ScpTa2PQZG9uuvFSUEJONlJSE-Xuizpe8pj6bGomfX2PD36TNG80oOdXEKm_JyIAMF4J3l23bfZI3KGDqfucrfSKEdJMMbc4JdiBb47_zf7g-hAQVD476TXjNh30JbS53PaR8DdBYrjbLWmo39NrxBJHZQSr0SexAtLY%3D")
                    //.header("cookie","hip=h1Dc1KHhGFZeez7PDglJ2Bu7ol5aAgAJpUL1z7eWXES9-LkOxh7LHliHkbcAo7FWg2YFEYVZVIiiotgVQP-N0xyKzu03jLSy25sdgfCrA4gaB5abv_3MEmO4knf3nvrNM9iP6eTPS8vvy9IFaCoAo20EyVxmAWxTryBXwmdINPJ6psdWQHk%3D")
                    .execute()
                    .body();

            if (html.equals("")) {
                   html = getHousingPrice(url,captchaUrl,captchaValidateUrl,validateUrl);
            }else {
                // 使用Jsoup解析HTML
                Document doc = Jsoup.parse(html);
                // 获取页面中第一个<div>元素属性
                Element firstDiv = doc.getElementsByClass("totalPrice").first();
                Element classValue = firstDiv.getElementsByTag("span").first();
                //尝试再调用一次
                if (StringUtils.isEmpty(classValue.html())) {
                    html = getHousingPrice(url,captchaUrl,captchaValidateUrl,validateUrl);
                }
            }
            // 使用Jsoup解析HTML
            Document doc = Jsoup.parse(html);
            // 获取页面中第一个<div>元素属性
            Element firstDiv = doc.getElementsByClass("totalPrice").first();
            Element classValue = firstDiv.getElementsByTag("span").first();
            // 输出结果
            return classValue.html();
        } catch (Exception e) {
            //log.error("获取到数据异常", e);
        }
        return "";
    }

    private static String getHousingPrice(String url,String captchaUrl,String captchaValidateUrl,String validateUrl) throws IOException {
        String html = "";
        //获取人机验证重定向url的 ext参数
        String ext = getRedirectedUrl(url);
        if (!ext.equals("0")){
            ext = getSubStr(ext,"ext=");
            // 获取验证码图片
            //生产随机数
            String randomString = RandomStringUtils.randomAlphanumeric(10);
            //生成 32位md5
            String token = MD5Util.MD5Encode(randomString, "utf-8");
            String jp = "__jp1";
            // 生成一个包含字母和数字的长度为10的随机字符串
            captchaUrl += token+"&callback="+jp;

            //获取验证码接口返回数据
            String captchaImage = getCaptchaImage(captchaUrl);

            //解析 base64转换为图片
            captchaImage = captchaImage.replace("/**/__jp1(","");
            captchaImage = captchaImage.replace(");","");
            JSONObject captchaJson = JSON.parseObject(captchaImage);
            JSONObject data = JSON.parseObject(captchaJson.get("data").toString());
            JSONObject puzzle = JSON.parseObject(data.get("puzzle").toString());
            String resource = puzzle.get("resource").toString();
            resource = resource.replace("data:image/jpeg;base64, ","");
            String fileImgPath = "";
            //判断系统
            String os = System.getProperty("os.name");
            if (os.contains("Windows")) {
                // 当前系统是Windows
                // 在这里编写针对Windows环境的代码逻辑
                fileImgPath = fileWinPath+token+".jpeg";
            } else if (os.contains("Linux")) {
                // 当前系统是Linux
                // 在这里编写针对Linux环境的代码逻辑
                fileImgPath = filePath+token+".jpeg";
            } else {
                // 未知系统
                // 在这里处理未知系统的情况
                fileImgPath = filePath+token+".jpeg";
            }


            //保存验证码图片
            File file = Base64ToFile.base64ToFile(resource,fileImgPath);

            //识别图片验证码
            String number = TPApiUtils.getCheckNumber(fileImgPath);

            //调用验证码验证接口
            captchaValidateUrl = captchaValidateUrl+token+"&challenger="+number+"&callback=__jp1"+jp;
            String result = getCaptchaValidate(captchaValidateUrl);
            if (result.contains("true")){
                //成功后继续调用获取 hip接口
                ValidVO vo = new ValidVO();
                vo.setToken(token);
                vo.setOrigin(null);
                vo.setScene("sec-hip");
                vo.setLocation("https://cq.ke.com/xiaoqu/rs");
                vo.setExt(ext);
                String jsonStr = JSON.toJSONString(vo);
                String hip = sendPostGetHip(validateUrl,jsonStr);
                if (StringUtils.isNotEmpty(hip)){
                    html = HttpUtil.createGet(url)
                            .header("cookie",hip)
                            .execute()
                            .body();
                }else {
                    log.info("hip获取失败！");
                }
            }else {
                log.info("调用校验验证码失败！重试");
                getHousingPrice(url,captchaUrl,captchaValidateUrl,validateUrl);
            }
        }else {
            log.info("获取重定向地址失败！");
        }
        return html;
    }

    //获取base64验证码 json数据
    private static String getCaptchaImage(String url) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getCaptchaValidate(String url) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取重定向后的地址
    public static String getRedirectedUrl(String url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setInstanceFollowRedirects(false); // 禁止自动处理重定向
        connection.setRequestMethod("GET");

        int statusCode = connection.getResponseCode();
        if (statusCode >= 300 && statusCode < 400) {
            String redirectedUrl = connection.getHeaderField("Location");
            return redirectedUrl;
        }
        return "0"; // 如果没有重定向，返回原始链接
    }

    //验证 token和验证码后获取 hip
    public static String sendPostGetHip(String url, String postdataJson) throws JsonProcessingException, UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);
        ObjectMapper objectMapper = new ObjectMapper();
        if(postdataJson != null) {
            StringEntity entity = new StringEntity(postdataJson, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
        }
        httpPost.setHeader("Content-type", "application/json"); // 设置内容类型为JSON
        //httpPost.setHeader("ss", "");
        //httpPost.setHeader("aa", "");
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            try (CloseableHttpResponse response = client.execute(httpPost)) {
               String hip = response.getHeaders("Set-Cookie")[0].getValue();
               //System.out.println(s);
                return hip;
                // 获取所有Set-Cookie头
//                List<String> setCookieHeaders = Arrays.asList(Arrays.toString(response.getHeaders("Set-Cookie")));
//                for (String header : setCookieHeaders) {
//                    System.out.println(header);
//                }
//                int status = response.getStatusLine().getStatusCode();
//                System.out.println("Status: " + status);
                //HttpEntity responseEntity = response.getEntity();
//                if (responseEntity != null) {
//                    String responseString = EntityUtils.toString(responseEntity);
//                    System.out.println("Response: " + responseString);
//                    //转换map
//                    //Map resultMap = objectMapper.readValue(responseString, Map.class);
//                    //System.out.println(resultMap);
//                    //return resultMap;
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //截取某个字符串的值
    public static String getSubStr(String url,String str){
        String originalString = url;
        String delimiter = str;
        String result = "";
        int delimiterIndex = originalString.indexOf(delimiter);
        if (delimiterIndex != -1) {
            result = originalString.substring(delimiterIndex + delimiter.length());
            //System.out.println(result); // 输出: World!
        } else {
            //System.out.println("Delimiter not found.");
        }
        return result;
    }

    /**
     * 获取安居客租房网搜索结果
     *
     * @param param 要搜索的关键字
     * @return 房源总价格
     */
//    public static String  getAnJuKeHousingResForSearch(String param) {
//        try {
//            // 从URL获取HTML内容
//
//            String html = HttpUtil.createGet("https://chongqing.anjuke.com/community/?kw=" + param).execute().body();
//
//            // 使用Jsoup解析HTML
//            Document doc = Jsoup.parse(html);
//            System.out.println(html);
//            // 获取页面中第一个<div>元素属性
////            Element firstDiv = doc.getElementsByClass("community-price").last();
////            Element classValue = firstDiv.getElementsByTag("strong").first();
//            Elements elements = doc.select("community-price");
//
//            // 输出结果
//            return elements.html();
//        } catch (Exception e) {
//            //log.error("获取到数据异常", e);
//        }
//        return "";
//    }

    public static void main(String[] args) throws IOException {
        //System.out.println(getBkeHousingResForSearch2("嘉悦广场"));

//        ValidVO vo = new ValidVO();
//        vo.setToken("nP88pmcrjR4czzFGrP7quzRKYVjHPmJu");
//        vo.setOrigin(null);
//        vo.setScene("sec-hip");
//        vo.setLocation("https://cq.ke.com/xiaoqu/rs");
//        vo.setExt("o9tVZ0jI3-qldKkAveLMXN5nQI_jqX6LAXXo059CHF-1PA819gtNRxE-Ec0y70QtuWk1FrZFxCIZdlgzc6QJo96pGqyQ3bTOnbTOLVJjJgUiZUYv7UOTHITBA0BPNSYp57VoZfXg");
//        String json = JSON.toJSONString(vo);
//        try {
//            sendPostJson("https://hip.ke.com/api/v1/validate",json);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
//        }


//        String ext = getRedirectedUrl("https://cq.ke.com/xiaoqu/rs");
//        String originalString = "https://hip.ke.com/captcha?location=https%3A%2F%2Fcq.ke.com%2Fxiaoqu%2Frs%2F&ext=o9tVZ0jI3-qldKkAveLMXN5nQI_jqX6LAXXo059CHF-1PA819gtNRxE-Ec0y70QtuWk1FrZFxCIZdlgzc6QJo96pGqyQ3bTOnbTOLVJjJgUiZUYv7UOTHITBA0BPNSYp57VoZfXg";
//        String delimiter = "ext=";
//        String extStr = getSubStr(ext,delimiter);
//        System.out.println(extStr);

        //test
        System.out.println(getBkeHousingResForSearch("嘉悦广场"));
    }

}
